<?php

namespace app\member\controller;

use app\member\model\UserRate;
use app\member\model\UserType;
use think\facade\Session;
use think\Db;
use app\pay\model\User as UserModel;
class User extends Base
{
	/**
	 *下级代理
	 */
	public function index()
	{
		$account = isset($_GET['account']) ? trim($_GET['account']) : '';
		$name = isset($_GET['name']) ? trim($_GET['name']) : '';
		$pid = intval($_GET['pid']);

		if (empty($pid)) {
			$this->error('参数错误!');
		}

		if (!empty($account) && empty($name)) {
			$map[] = ['agent_account', 'like', '%' . $account . '%'];
		}
		if (empty($account) && !empty($name)) {
			$map[] = ['agent_name', 'like', '%' . $name . '%'];

		}
		if (!empty($account) && !empty($name)) {
			$map[] = ['agent_account', 'like', '%' . $account . '%'];
			$map[] = ['agent_name', 'like', '%' . $name . '%'];
		}
		$map[] = ['agent_pid', 'eq', $pid];

		$list = Db::name('Agent')
			->where($map)
			->paginate();

		$todymoney = Db::name('AgentProfit')->where('profit_time', '>', strtotime(date("Y-m-d"), time()))->where('profit_agent_id', $pid)->sum('profit_amount');
		//今日分润
		$todyprofit = Db::name('AgentProfit')->where('profit_time', '>', strtotime(date("Y-m-d"), time()))->where('profit_agent_id', $pid)->sum('profit_money');
		//总消费额
		$sunmoney = Db::name('AgentProfit')->where('profit_agent_id', $pid)->sum('profit_amount');
		//总分润
		$sunprofit = Db::name('AgentProfit')->where('profit_agent_id', $pid)->sum('profit_money');
		$this->assign('todymoney', $todymoney);
		$this->assign('todyprofit', $todyprofit);
		$this->assign('sunmoney', $sunmoney);
		$this->assign('sunprofit', $sunprofit);
		$this->assign('account', $account);
		$this->assign('name', $name);
		$this->assign('list', $list);
		return view();
	}

	// 个人推广码
	public function excode()
	{
		$code = Db::name('agent')->where('agent_id', session::get('agent_id'))->value('agent_code');
		if (!$code) {
			return json(['msg' => '数据不存在!', 'error' => '0']);
		}
		$url = 'http://' . $_SERVER['HTTP_HOST'] . '?id=' . $code;

		$this->assign('urls', $url);
		return view();
	}

	// 代理商管理
	public function agentlist()
	{
		$account = isset($_GET['account']) ? trim($_GET['account']) : '';
		$name = isset($_GET['name']) ? trim($_GET['name']) : '';
		$pid = session::get('member_id');

		if (!empty($account) && empty($name)) {
			$map[] = ['user_account', 'like', '%' . $account . '%'];
		}
		if (empty($account) && !empty($name)) {
			$map[] = ['user_name', 'like', '%' . $name . '%'];

		}
		if (!empty($account) && !empty($name)) {
			$map[] = ['user_account', 'like', '%' . $account . '%'];
			$map[] = ['user_name', 'like', '%' . $name . '%'];
		}
		$map[] = ['user_pid', 'eq', $pid];

		$list = Db::name('user')
			->where($map)
			->paginate();


		$this->assign('account', $account);
		$this->assign('name', $name);
		$this->assign('list', $list);
		return view();
	}

	// 删除代理商
	public function agent_del()
	{
		$aid = input('get.aid');
		if ($aid == '') {
			return json(['msg' => '参数错误!', 'error' => 1]);
		}

		Db::name('Agent')->where(array('agent_id' => $aid))->delete();
		return json(['msg' => '操作完成!', 'error' => 0]);
	}

	/**
	 * 用户列表
	 */
	public function userlist()
	{
		$account = isset($_GET['account']) ? trim($_GET['account']) : '';
		$name = isset($_GET['name']) ? trim($_GET['name']) : '';
		$pid = session::get('member_id');

		if (!empty($account) && empty($name)) {
			$map[] = ['u.user_account', 'like', '%' . $account . '%'];
		}
		if (empty($account) && !empty($name)) {
			$map[] = ['u.user_name', 'like', '%' . $name . '%'];

		}
		if (!empty($account) && !empty($name)) {
			$map[] = ['u.user_account', 'like', '%' . $account . '%'];
			$map[] = ['u.user_name', 'like', '%' . $name . '%'];
		}
		$map[] = ['user_pid', 'eq', $pid];
		$list = Db::name('User as u')->join('UserType t', 'u.user_type_id=t.type_id')->where($map)->paginate();
		// $list = Db::name('User')->where($map)->paginate();

		$this->assign('account', $account);
		$this->assign('name', $name);
		$this->assign('pid', $pid);
		$this->assign('list', $list);
		return view();
	}

	// 个人资料
	public function info()
	{
		if ($this->request->isPost()) {
			$post = input('post.');

			if ($post['user_name'] == '' || $post['user_phone'] == '' || $post['user_idcard'] == '') {
				return json(['msg' => '请填写完整信息!', 'error' => '1']);
			}
			Db::name('user')->where(array('user_id' => $this->user['user_id']))->update($post);
			return json(['msg' => '已保存!', 'error' => 0]);
		}

		$userinfo = Db::name('user')->where(array('user_id' => $this->member['user_id']))->find();
		$this->assign('userinfo', $userinfo);
		return view();
	}

	// 我的成本
	public function getagreta()
	{
		$typeList = Db::name("user_type")->select();//halt($typeList);
		foreach ($typeList as &$item) {
			$item["hk_rate"] = Db::name("rate")->where(["rate_type_id"=>$item["type_id"],"rate_type"=>'1'])->value("rate_rate");
			$item["sk_rate"] = Db::name("rate")->where(["rate_type_id"=>$item["type_id"],"rate_type"=>'2'])->value("rate_rate");
		}
		$this->assign("typeList", $typeList);
		return $this->fetch();
	}

	/*
	* 修改账户密码
	*
	*/
	public function updapass()
	{
		if ($this->request->isPost()) {
			$post = input('post.');
			if ($post['pass'] == '' || $post['repass'] == '' || $post['ispass'] == '') {
				return json(['msg' => '请填写完整信息!', 'error' => '1']);
			}

			if (md5($post['pass']) !== $this->agent['agent_password']) {
				return json(['msg' => '原密码输入错误!', 'error' => '1']);
			}

			if ($post['pass'] == $post['repass']) {
				return json(['msg' => '新密码不可与原密码一致!', 'error' => '1']);
			}

			if ($post['repass'] !== $post['ispass']) {
				return json(['msg' => '确认密码输入不一致!', 'error' => '1']);
			}

			$passwd = md5($post['repass']);
			Db::name('agent')->where(array('agent_id' => $this->agent['agent_id']))->update(array('agent_password' => $passwd));

			// 清除用户登录信息，重新登录
			Session::clear();
			session_unset();

			return json(['msg' => '操作完成!', 'error' => '0']);
		}

		return view();
	}

	/**
	 * 首页报表
	 *
	 * @param string $name [description]
	 *
	 * @return [type]       [description]
	 */
	public function console()
	{
		return view();
	}

	/**
	 * 下级客户
	 */
	public function User()
	{
		$account = isset($_GET['account']) ? trim($_GET['account']) : '';
		$name = isset($_GET['name']) ? trim($_GET['name']) : '';
		$pid = isset($_GET['pid']) ? intval($_GET['pid']) : 0;

		if (!empty($account) && empty($name)) {
			$map[] = ['u.user_account', 'like', '%' . $account . '%'];
		}
		if (empty($account) && !empty($name)) {
			$map[] = ['u.user_name', 'like', '%' . $name . '%'];

		}
		if (!empty($account) && !empty($name)) {
			$map[] = ['u.user_account', 'like', '%' . $account . '%'];
			$map[] = ['u.user_name', 'like', '%' . $name . '%'];
		}
		$map[] = ['u.user_agent_id', 'eq', $pid];
		$list = Db::name('User as u')
			->join('UserType t', 'u.user_type_id=t.type_id')
			->where($map)
			->paginate();

		$pname = Db::name('user')->where('user_id', $pid)->value('user_name');
		if (!$pname) {
			$pname = Db::name('user')->where('user_id', $pid)->value('user_account');
		}
		$this->assign('pname', $pname);
		$this->assign('account', $account);
		$this->assign('name', $name);
		$this->assign('pid', $pid);
		$this->assign('list', $list);
		return view();
	}

	/**
	 * 新增代理
	 */
	public function Addagent()
	{
		if($this->member["user_type_id"] <= '2'){
			$this->error("请先升级更高级别才可以开会员",url("user/getagreta"));
		}
		$typeList = (new UserType())->getList($this->member["user_type_id"]);

		if ($this->request->isPost()) {
			$post = input('post.');
			if (empty($post)) {
				return json(['error' => 1, 'msg' => '参数错误']);
			}

			if(empty($post["grade_id"])){
				return json(['error' => 1, 'msg' => '请选择等级']);
			}else{
				if($post["grade_id"]>=$this->member["user_type_id"]){
					return json(['error' => 1, 'msg' => '选择等级错误']);
				}
			}


			//检查代理是否存在
			$agentacc = Db::name('user')->where(['user_account' => trim($post['account']), 'user_name' => trim($post['name'])])->find();
			if ($agentacc) {
				return json(['error' => 1, 'msg' => '该代理已存在']);
			}

			//检查是否有权限再开相应等级
			if($this->member["user_type_id"]=="4"){
				$count = (new UserModel)->where(["user_pid"=>$this->member["user_id"],"user_type_id"=>3])->count("user_id");
				if($count>=20){
					return json(['error' => 1, 'msg' => '您的可用承载量不足，无法进行下级代理划分']);
				}
			}
			//数据添加.
			$data = array();
			$data['user_code'] = rand(1000, 9999);
			$data['user_pid'] = session::get('member_id');
			$data['user_account'] = trim($post['account']);
			$data['user_password'] = md5(trim($post['password']));
			$data['user_name'] = trim($post['name']);
			$data['user_phone'] = trim($post['phone']);
			$data['user_idcard'] = trim($post['idcard']);
			$data['user_state'] = 0;
			$data['user_time'] = time();
			$data['user_ip'] = get_client_ip6();
			$data['user_type_id'] = $post["grade_id"];
			$res = Db::name('User')->insertGetId($data);
			if ($res) {
				//找到当前升级等级的费率
				$hk_rate = (new UserModel)->getUserRankConfig($post["grade_id"]);
				$sk_rate = "0.0055";
				$result1 = Db::name('UserRate')->insert(['rate_uid' => $res, 'rate_rate' => $hk_rate, 'rate_close_rate'=>2, 'rate_type' => 1, 'rate_time' => time()]);
				$result2 = Db::name('UserRate')->insert(['rate_uid' => $res, 'rate_rate' => $sk_rate, 'rate_close_rate'=>2, 'rate_type' => 2, 'rate_time' => time()]);
				if ($result1 && $result2) {
					return json(['error' => 0, 'msg' => '添加成功']);
				}
			} else {
				return json(['error' => 1, 'msg' => '添加失败']);
			}
		} else {

			$this->assign('typeList', $typeList);
			return view();
		}
	}

	/**
	 * 代理信息修改
	 */
	public function Upagent()
	{
		if ($this->request->isPost()) {
			$post = input('post.');
			if (empty($post)) {
				return json(['error' => 1, 'msg' => '参数错误']);
			}

			if(empty($post["grade_id"])){
				return json(['error' => 1, 'msg' => '请选择等级']);
			}else{
				if($post["grade_id"]>=$this->member["user_type_id"]){
					return json(['error' => 1, 'msg' => '选择等级错误']);
				}
			}

			//检查是否有权限再开相应等级
			if($this->member["user_type_id"]=="4"){
				$count = (new UserModel)->where(["user_pid"=>$this->member["user_id"],"user_type_id"=>3])->count("user_id");
				if($count>=20){
					return json(['error' => 1, 'msg' => '您的可用承载量不足，无法进行下级代理划分']);
				}
			}


			$sonagent = Db::name('user')->where(['user_id' => $post['agid'], 'user_pid' => session::get('member_id')])->find();
			if (empty($sonagent)) {
				return json(['error' => 1, 'msg' => '查无此会员信息']);
			}

			$data = array();
			$data['user_name'] = trim($post['name']);
			$data['user_phone'] = trim($post['phone']);
			$data['user_idcard'] = trim($post['idcard']);
			$data['user_type_id'] = $post["grade_id"];
			$res = Db::name('user')->where('user_id', $post['agid'])->update($data);


			//找到当前升级等级的费率
			$hk_rate = (new UserModel)->getUserRankConfig($post["grade_id"]);
			$sk_rate = "0.0055";
			$result = Db::name('UserRate')->where(['rate_uid' => $post['agid'], 'rate_type' => 1])->update(['rate_rate' => $hk_rate]);
			$result1 = Db::name('UserRate')->where(['rate_uid' => $post['agid'], 'rate_type' => 2])->update(['rate_rate' => $sk_rate]);


			if ($result || $result1 || $res) {
				return json(['error' => 0, 'msg' => '修改成功']);
			} else {
				return json(['error' => 1, 'msg' => '修改失败']);
			}


		} else {
			if (isset($_GET['id'])) {
				$userinfo = Db::name('user')
					->where('user_id', intval($_GET['id']))
					->find();
				if (empty($userinfo)) {
					return json(['error' => 1, 'msg' => '查无此会员信息']);
				}
				$typeList = (new UserType())->getList(0);

				$rate = (new UserRate())->getRateByUid(intval($_GET['id']));//halt($rate);
				$this->assign('rate', $rate);
				$this->assign('userinfo', $userinfo);
				$this->assign('typeList', $typeList);
				return view();

			} else {
				return json(['error' => 1, 'msg' => '参数错误']);
			}
		}
	}
}
